/**
 * @功能插件
 */
import { ref, computed } from 'vue'
import { searchUsers, type User } from '@/apis/methods/comment.api'

// 临时类型定义，避免类型错误
type SearchResponse = {
  code: number
  message: string
  data: User[]
}

export interface MentionPluginOptions {
  debounceTime?: number
  maxSuggestions?: number
}

export function useMentionPlugin(options: MentionPluginOptions = {}) {
  const { debounceTime = 300, maxSuggestions = 10 } = options

  const suggestions = ref<User[]>([])
  const showSuggestions = ref(false)
  const mentionedUsers = ref<string[]>([])
  const searchTimeout = ref<number>()

  // 搜索用户
  const searchUsersDebounced = async (query: string) => {
    if (searchTimeout.value) {
      clearTimeout(searchTimeout.value)
    }

    searchTimeout.value = window.setTimeout(async () => {
      try {
        if (query.length === 0) {
          const response = (await searchUsers({
            limit: maxSuggestions,
          })) as unknown as SearchResponse
          if (response.code === 200) {
            suggestions.value = response.data
            showSuggestions.value = suggestions.value.length > 0
          }
          return
        }

        if (query.length > 0) {
          const response = (await searchUsers({
            q: query,
            limit: maxSuggestions,
          })) as unknown as SearchResponse
          if (response.code === 200) {
            suggestions.value = response.data
            showSuggestions.value = suggestions.value.length > 0
          }
        }
      } catch (error) {
        console.error('搜索用户失败:', error)
        suggestions.value = []
        showSuggestions.value = false
      }
    }, debounceTime)
  }

  // 处理输入变化
  const handleInput = (text: string) => {
    const atIndex = text.lastIndexOf('@')
    if (atIndex === -1) {
      showSuggestions.value = false
      return
    }

    const query = text.slice(atIndex + 1)
    searchUsersDebounced(query)
  }

  // @用户
  const mentionUser = (user: User, contentRef?: { value: string }) => {
    if (contentRef) {
      const atIndex = contentRef.value.lastIndexOf('@')
      if (atIndex !== -1) {
        contentRef.value = contentRef.value.slice(0, atIndex) + `@${user.username} `
      }
    }

    if (!mentionedUsers.value.includes(user.id)) {
      mentionedUsers.value.push(user.id)
    }

    showSuggestions.value = false
  }

  // 清除建议
  const clearSuggestions = () => {
    showSuggestions.value = false
    suggestions.value = []
  }

  // 清除@用户
  const clearMentionedUsers = () => {
    mentionedUsers.value = []
  }

  return {
    suggestions: computed(() => suggestions.value),
    showSuggestions: computed(() => showSuggestions.value),
    mentionedUsers,
    handleInput,
    mentionUser,
    clearSuggestions,
    clearMentionedUsers,
  }
}
